package org.esky.xml;

import java.util.Stack;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxXMLReader extends DefaultHandler {
	@SuppressWarnings("rawtypes")
	Stack tags = new Stack();
	
	public SaxXMLReader() {
	}

	/**
	 * SAX方式
	 * 
	 * @Title: reader
	 * @Description: TODO
	 * @return: void
	 */
	public static void reader(String path) {
		long lasting = System.currentTimeMillis();
		try {
			SAXParserFactory sf = SAXParserFactory.newInstance();
			SAXParser sp = sf.newSAXParser();
			SaxXMLReader reader = new SaxXMLReader();
			sp.parse(new InputSource(path), reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("SAX RUNTIME：" + (System.currentTimeMillis() - lasting) + " MS");
	}

	@Override
	public void characters(char ch[], int start, int length) throws SAXException {
		String tag = (String) tags.peek();
		if (tag.equals("name")) {
			System.out.println("|| Name:  |" + new String(ch, start, length));
		}
		if (tag.equals("space")) {
			System.out.println("||Space:  |" + new String(ch, start, length));
		}
		System.out.println("-------------------------------------------------");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
		tags.push(qName);
	}

}
